package com.uduemc.biso.core.utils;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class ResultUtil {

	public static boolean ok(RestResult restResult) {
		if (restResult.getCode() == 200) {
			return true;
		}
		return false;
	}

	public static boolean dataOk(RestResult restResult) {
		if (ok(restResult) && restResult.getData() != null) {
			return true;
		}
		return false;
	}

	public static Object data(RestResult restResult) {
		if (dataOk(restResult)) {
			return restResult.getData();
		}
		return null;
	}

	public static Object data(RestResult restResult, JavaType valueType)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		if (dataOk(restResult)) {
			ObjectMapper objectMapper = new ObjectMapper();
			return objectMapper.readValue(objectMapper.writeValueAsString(restResult.getData()), valueType);
		}
		return null;
	}

	public static Object data(RestResult restResult, TypeReference<?> valueTypeRef)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		if (dataOk(restResult)) {
			ObjectMapper objectMapper = new ObjectMapper();
			return objectMapper.readValue(objectMapper.writeValueAsString(restResult.getData()), valueTypeRef);
		}
		return null;
	}

	public static <T> T data(RestResult restResult, Class<T> class1)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		if (dataOk(restResult)) {
			ObjectMapper objectMapper = new ObjectMapper();
			return objectMapper.readValue(objectMapper.writeValueAsString(restResult.getData()), class1);
		}
		return null;
	}

	public static <T> T data(RestResult restResult, Class<T> class1, boolean isDelete)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {

		if (isDelete) {
			if (ok(restResult)) {
				ObjectMapper objectMapper = new ObjectMapper();
				return objectMapper.readValue(objectMapper.writeValueAsString(restResult.getData()), class1);
			}
		} else {
			return data(restResult, class1);
		}
		return null;
	}
}
